<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--优惠券-->
			<view class="detail-item">
				<uni-section title="指定发放优惠券" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
					  <uni-forms-item label="最低消费" name="minConsume" required>
					    <uni-easyinput type="number" v-model="formData.minConsume" placeholder="请输入最低消费" />
					  </uni-forms-item>
						<uni-forms-item label="抵扣金额" name="discountMoney" required>
						  <uni-easyinput type="number" v-model="formData.discountMoney" placeholder="请输入抵扣金额" />
						</uni-forms-item>
						<uni-forms-item label="发放顾客" name="giveOut" required>
							<view class="tags main-flex">
								<up-tag
									class="tags-item"
									:text="`${item.customerName}(${item.customerId})`"
									size="mini"
									v-for="item in formData.couponRecordList" :key="item.customerId"></up-tag>
								<up-tag class="tags-item" text="选择" size="mini" @click="openCustomer">
									<template v-slot:icon>
										<up-icon name="plus" color="#FFFFFF" size="16"></up-icon>
									</template>
								</up-tag>
								<up-tag class="tags-item" text="清空" size="mini" type="error" @click="clearCustomer">
									<template v-slot:icon>
										<up-icon name="trash" color="#FFFFFF" size="16"></up-icon>
									</template>
								</up-tag>
							</view>
							<uni-easyinput style="display: none;" v-model="formData.giveOut" placeholder="请选择发放顾客" />
						</uni-forms-item>
						<uni-forms-item label="开始时间" name="startTime" required>
							<uni-datetime-picker type="datetime" placeholder="请选择有效期开始时间" v-model="formData.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间" name="endTime" required>
							<uni-datetime-picker type="datetime" placeholder="请选择有效期结束时间" v-model="formData.endTime"/>
						</uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
		
		<ty-customer-picker
			@close="closeCustomer"
			@change="changeCustomer"
			:showCustomer="showCustomer"></ty-customer-picker>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import { timeFormat } from 'uview-plus'
import { couponAdd, couponDetail, marketPlanPerson } from "@/api/erp_api/coupon"
import { upload } from "@/api/system/common"
import { couponTypeList } from '@/utils/config.js'
import { customer } from "@/api/erp_api/customer"
import tyColorPicker from '@/components/ty-color-picker/ty-color-picker.vue'
import { getRecentDays } from '@/utils/ty.js'

	const userStore = useUserStore()
	onLoad((option) => {
		// if (userStore?.user?.userId) {
		// 	getMarketPlanPerson()
		// }
	})
	
	// 预算
	const marketPlanPersonObj = ref({})
	const getMarketPlanPerson = () => {
		marketPlanPerson({
			planMonth: timeFormat(new Date(), 'ym'),
			regionCode: userStore.regionCode,
			userId: userStore.user.userId,
			pageNum: 1,
			pageSize: 100
		}).then(res => {
			marketPlanPersonObj.value = res.rows?.[0] || {}
		})
	}
	
	
	// 发放顾客
	const showCustomer = ref(false)
	const openCustomer = () => {
		showCustomer.value = true
	}
	const closeCustomer = () => {
		showCustomer.value = false
	}
	
	// 清空
	const clearCustomer = () => {
		formData.value.couponRecordList = []
		formData.value.totalNumber = ''
		formData.value.giveOut = ''
	}
	
	const changeCustomer = (e) => {
		const chooseCustomerId = formData.value.couponRecordList.map(item => item.customerId)
		const customerList = e.filter(item => chooseCustomerId.indexOf(item.id) === -1)
		formData.value.couponRecordList = formData.value.couponRecordList.concat(customerList.map(item => {
			return {
				customerId: item.id,
				customerName: item.name
			}
		}))
		formData.value.totalNumber = e.length
		formData.value.giveOut = formData.value.couponRecordList.map(item => `${item.customerName}(${item.customerId})`).join(',')
	}
	
	// form表单数据
	const formData = ref({
		name: '',
		minConsume: 100,
		backColor: '',
		backImg: '',
		ad: '',
		discountMoney: '',
		couponRecordList: [],
		remark: '',
		accumulationFlag: 0,
		integralValue: '',
		saleFlag: 0,
		totalNumber: '',
		type: '',
		endTime: `${getRecentDays(-1)} 00:00:00`,
		startTime: `${timeFormat(new Date(), 'yyyy-mm-dd')} 00:00:00`,
		giveOut: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		minConsume: {
			rules: [{ required: true, errorMessage: '请输入最低消费' }]
		},
		discountMoney: {
			rules: [{ required: true, errorMessage: '请输入抵扣金额' }]
		},
		startTime: {
			rules: [{ required: true, errorMessage: '请选择有效期开始时间' }]
		},
		endTime: {
			rules: [{ required: true, errorMessage: '请选择有效期结束时间' }]
		},
		giveOut: {
			rules: [
				{ required: true, errorMessage: '请选择发放顾客' },
				{ 
					validateFunction:function(rule,value,data,callback){
						if (formData.value.couponRecordList.length > 1) {
							callback('只能选择一个顾客')
						}
						return true
					}
				}
			]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			isSubmit.value = true
			const params = { 
				...formData.value,
				name: `满${formData.value.minConsume}减${formData.value.discountMoney}`,
				regionCode: userStore.regionCode,
				subType: 3
			}
			couponAdd(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			name: '',
			minConsume: 100,
			backColor: '',
			backImg: '',
			ad: '',
			discountMoney: '',
			couponRecordList: [],
			remark: '',
			accumulationFlag: 0,
			integralValue: '',
			saleFlag: 0,
			totalNumber: '',
			type: '',
			endTime: '',
			startTime: '',
			giveOut: ''
		}
	}
	
	// watch(() => userStore.user.userId, (nval, oval) => {
	// 	if (nval) {
	// 		getMarketPlanPerson()
	// 	}
	// },{ immediate: true })
</script>

<style scoped lang="scss">
	.tags {
		flex-wrap: wrap;
		min-height: 100%;
		margin: 0 -4px;
		&-item {
			margin: 4px;
		}
	}
	.search {
		margin-top: 0;
	}
</style>
